/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.apache;

import nfse.NetFSE;
import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;

import java.sql.Timestamp;
import java.util.*;

public class Apache2AccessRecord extends NetFSERecord {

    public String dstAddr = "";

    public long dstIP = -1;

    public long bytes = 0;

    public String userName = "";

    public int httpCode = -1;

    public String getRequest = "";

    public String url = "";

    public String userAgent = "";

    public Timestamp stopTS = null;

    public Apache2AccessRecord() {

    }
    
    public static void main(String[] args) {
        Apache2AccessRecord rec = new Apache2AccessRecord();
        rec.parse(args, rec);
    }

    public long getDstIP() {
        return dstIP;
    }

    public void setDstIP(long dstIP) {
        this.dstIP = dstIP;
        this.dstAddr = NetFSEUtil.convertLongToIP(dstIP);
    }

    public Apache2AccessRecord(int sensor) {
        this.setSensorID(sensor);
    }

    public String get(int field) {
        String temp = "";
        int len = 0;
        switch (field) {
        case (NetFSE.FIELD_START_TS):
            temp = Long.toHexString(this.getTimestamp().getTime() / 1000);
            len = 8;
            break;
        case (NetFSE.FIELD_DST_IP):
            temp = Long.toHexString(this.dstIP);
            len = 8;
            break;
        case (NetFSE.FIELD_SRC_IP):
            temp = Long.toHexString(this.getSrcIP());
            len = 8;
            break;
        default:
            temp = null;
            break;
        }
        if (temp != null) {
            while (temp.length() < len)
                temp = "0" + temp;
        }
        return temp;
    }

    public NetFSERecord generate(String line, int sensor) {
        try {

            // 192.168.0.50 - ben [23/Jan/2008:14:58:21 -0700] "GET /trac
            // HTTP/1.1" 200
            // 6415 "-" "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en)
            // AppleWebKit/523.12.2 (KHTML, like Gecko) Version/3.0.4
            // Safari/523.12.2"

            Apache2AccessRecord rec = new Apache2AccessRecord(sensor);

            rec.setSensorID(sensor);

            int idx1 = line.indexOf(";");
            int idx2 = line.indexOf(";", idx1 + 2);
            int colIdx = line.indexOf(":", idx2 + 15);

            String dstIP = line.substring(idx1 + 1, idx2);
            if (!dstIP.equals("-1")) {
                rec.setDstIP(NetFSEUtil.convertIPtoLong(dstIP));
            }

            String tsStr = line.substring(0, idx1);
            if (!tsStr.equals("-1")) {
                java.sql.Timestamp ts = new java.sql.Timestamp(Long.parseLong(tsStr) * 1000);
                rec.setStartTS(ts);
            } else {
                tsStr = line.substring(idx2, colIdx);
                java.sql.Timestamp ts = NetFSEUtil.timestampFromSyslog(tsStr);
                rec.setStartTS(ts);
                line = ts.getTime() / 1000 + line.substring(idx1);
                idx1 = line.indexOf(";");
                idx2 = line.indexOf(";", idx1 + 2);
                colIdx = line.indexOf(":", idx2 + 15);
            }

            StringTokenizer st = new StringTokenizer(line.substring(colIdx + 1).trim(), "\"");

            String token1 = st.nextToken();

            String[] headerTokens = token1.trim().split(" +");
            rec.setSrcIP(NetFSEUtil.convertIPtoLong(headerTokens[0]));
            rec.userName = headerTokens[2];

            headerTokens[3] = headerTokens[3].substring(1);
            int tsColIdx = headerTokens[3].indexOf(":");
            String[] dtTokens = headerTokens[3].substring(0, tsColIdx).split("/");
            String[] timeTokens = headerTokens[3].substring(tsColIdx + 1).split(":");
            GregorianCalendar cal = new GregorianCalendar();
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dtTokens[0]));
            cal.set(Calendar.MONTH, NetFSE.getMonthValue(dtTokens[1]));
            cal.set(Calendar.YEAR, Integer.parseInt(dtTokens[2]));
            cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeTokens[0]));
            cal.set(Calendar.MINUTE, NetFSE.getMonthValue(timeTokens[1]));
            cal.set(Calendar.SECOND, Integer.parseInt(timeTokens[2]));

            TimeZone tz = TimeZone.getTimeZone("GMT" + headerTokens[4]);
            cal.setTimeZone(tz);

            rec.setStartTS(new Timestamp(cal.getTimeInMillis()));

            rec.getRequest = st.nextToken();

            String token2 = st.nextToken().trim();
            int idx = token2.indexOf(" ");

            rec.httpCode = Integer.parseInt(token2.substring(0, idx));
            rec.bytes = Integer.parseInt(token2.substring(idx + 1));
            rec.url = st.nextToken();

            String token4 = st.nextToken(); // White space
            rec.userAgent = st.nextToken().trim();

            rec.setInitialString(line);

            
            return rec;
        } catch (Exception E) {
            E.printStackTrace();
        }
        return null;
    }

    public String getCreateFieldTableSQL(String table) {
        StringBuffer temp = new StringBuffer("create table " + table + " (ID bigint, ");
        temp.append("srcip inet,");
        temp.append("dstip inet,");
        temp.append("username varchar(50),");
        temp.append("useragent varchar(255),");
        temp.append("getrequest varchar(255),");
        temp.append("url varchar(255),");
        temp.append("httpcode integer,");
        temp.append("bytes bigint,");
        temp.append("startts timestamp,");
        temp.append("endts timestamp");
        temp.append(")");
        return temp.toString();
    }

    public FlexRecord getFlexRecord() {
        FlexRecord temp = new FlexRecord();
        temp.values = new String[9];
        int idx = -1;
        temp.values[++idx] = this.getTimestamp().toString();
        //temp.values[++idx] = this.stopTS.toString();
        temp.values[++idx] = this.getSrcAddr();
        temp.values[++idx] = this.dstAddr;
        temp.values[++idx] = this.userName + "";
        temp.values[++idx] = this.userAgent + "";
        temp.values[++idx] = this.url + "";
        temp.values[++idx] = this.getRequest + "";
        temp.values[++idx] = this.httpCode + "";
        temp.values[++idx] = this.bytes + "";
        return temp;
    }

    public FlexRecordField[] getFlexRecordFields() {
        FlexRecordField[] temp = new FlexRecordField[9];
        int idx = -1;
        temp[++idx] = new FlexRecordField("Start TS", "startts", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_TIMESTAMP);
        //temp[++idx] = new FlexRecordField("Stop TS", "endts", FlexRecordField.TYPE_STRING,
         //       FlexRecordField.SUB_TYPE_TIMESTAMP);
        temp[++idx] = new FlexRecordField("Src IP", "srcip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("Dst IP", "dstip", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_IP_ADDR);
        temp[++idx] = new FlexRecordField("User", "username", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("User Agent", "useragent", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("URL", "url", FlexRecordField.TYPE_STRING, FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Get Request", "getrequest", FlexRecordField.TYPE_STRING,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("HTTP Code", "httpcode", FlexRecordField.TYPE_INT,
                FlexRecordField.SUB_TYPE_NONE);
        temp[++idx] = new FlexRecordField("Bytes", "bytes", FlexRecordField.TYPE_INT, FlexRecordField.SUB_TYPE_NONE);
        return temp;
    }

    public String getInsertFieldTableSQL(int id, String table) {
        StringBuffer temp = new StringBuffer("insert into " + table + " values (" + id + "");
        temp.append(",'");
        temp.append(getSrcAddr() + "'");
        temp.append(",'");
        temp.append(dstAddr + "'");
        temp.append(",");
        temp.append("'" + userName + "'");
        temp.append(",");
        temp.append("'" + userAgent + "'");
        temp.append(",");
        temp.append("'" + url + "'");
        temp.append(",");
        temp.append("'" + getRequest + "'");
        temp.append(",");
        temp.append("" + httpCode + "");
        temp.append(",");
        temp.append("" + bytes + "");
        temp.append(",");
        temp.append("'" + getTimestamp().toString() + "'");
        //temp.append(",");
        //temp.append("'" + stopTS.toString() + "'");
        temp.append(")");
        return temp.toString();
    }

    public boolean isSyslog() {
        return true;
    }

    public int[] getIndexedFields() {
        int[] temp = { NetFSE.FIELD_START_TS, NetFSE.FIELD_SRC_IP, NetFSE.FIELD_DST_IP };
        return temp;
    }

}